from flask import Blueprint, render_template, request, url_for, session, g
from flask_login import login_required, login_user, logout_user
from flask_restful import reqparse, abort, Api, Resource
from functools import wraps
import re

from myflaskapp.user.models import User, Role, Sbu
from myflaskapp.extensions import auth, login_manager

blueprint = Blueprint(
    'api', __name__, static_folder='../static', static_url_path='')

api = Api(blueprint)

def check_role(rolename):
    def decrator(func):
        @wraps(func)
        def wrapper(*args,**kwargs):
            if g.current_user.role.name == rolename:
                return func(*args,**kwargs)
            else:
                return {'code': 1, 'message': "无此权限！"}
        return wrapper
    return decrator

@auth.verify_password
def verify_password(account, password):
    if account and password:
        user = User.query.filter_by(username=account).first()
        if user is not None and user.verify_password(password):
            g.current_user = user
            return True
        else:
            return False
    else:
        token = request.headers.get('X-Token')
        if token == '':
            return False
        else:
            user = User.verify_auth_token(token)
            g.current_user = user
            if 'username' in session and session['username'] is not None:
                return session['username'] == user.id
            else:
                return False


parser = reqparse.RequestParser()
parser.add_argument('username')
parser.add_argument('password')


class Login(Resource):

    def get(self):
        return {'success': 0}

    def post(self):
        args = parser.parse_args()
        user = User.query.filter_by(username=args['username']).first()
        if user is not None and user.verify_password(args['password']):
            login_user(user)
            session['username'] = user.id
            return {'success': 1}
        else:
            return {'success': 0}


class Logout(Resource):
    @auth.login_required
    def post(self):
        logout_user()
        session['username'] = None
        return {'code': 20000, 'data': 'success'}


class Token(Resource):
    @login_required
    def get(self):
        token = User.query.filter_by(id=session['username']).first(
        ).generate_auth_token(expiration=5400)
        return {'code': 20000, 'data': {'token': token}}


class Roleget(Resource):
    @auth.login_required
    def get(self):
        role = User.query.filter_by(id=session['username']).first().role
        if not role:
            return {'code': 60204, 'message': '非法用户，无法获取角色'}
        else:
            data = {}
            data['roles'] = [role.name]
            data['introduction'] = role.introduction
            data['avatar'] = 'https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif'
            data['name'] = [role.name]
            return {'code': 20000, 'data': data}


class Test(Resource):
    def get(self):
        return {'data': 'success'}


class Accountlist(Resource):
    @auth.login_required
    @check_role('admin')
    def get(self):
        users = User.query.all()
        data = []
        for user in users:
            info = {}
            info['username'] = user.username
            info['chinese_name'] = user.chinese_name
            info['role'] = user.role.introduction
            info['zhiwu'] = user.zhiwu
            info['bumen'] = user.bumen
            info['sbu'] = user.sbu.name
            data.append(info)
        return {'code': 20000, 'data': {'items': data}}

    @auth.login_required
    @check_role('admin')
    def post(self):
        userinfo = request.get_json()
        print(userinfo)
        regx = re.compile(r'.*\s+.*')
        if userinfo['isEdit'] == 0:
            if not  userinfo["username"] or not userinfo["password"] or not userinfo["role"] or not userinfo["chinese_name"] or not userinfo['bumen'] or not userinfo['zhiwu'] or not userinfo['sbu']:
                return {'code': 1, 'message': "请认真填写每一项！"}
            if regx.match("%s,%s,%s" % (userinfo["username"], userinfo["password"], userinfo["chinese_name"])):
                return {'code': 1, 'message': "请注意，用户名、密码、姓名中不能有空格！"}
            userrole = Role.query.filter_by(
                introduction=userinfo["role"]).first()
            sbu = Sbu.query.filter_by(name=userinfo['sbu']).first()
            if not userrole:
                return {'code': 1, 'message': "无此用户角色，请填写正确内容！"}
            try:
                User.create(username=userinfo["username"], password=userinfo["password"],
                            chinese_name=userinfo["chinese_name"], role=userrole, sbu=sbu,
                            zhiwu = userinfo['zhiwu'], bumen = userinfo['bumen'])
            except Exception:
                return {'code': 1, 'message': "账户名重复或其他项存在非法字符！"}
        else:
            user = User.query.filter_by(username=userinfo['username']).first()
            if not user:
                return {'code': 1, 'message': "改用户不存在！"}
            if userinfo['role']:
                userrole = Role.query.filter_by(
                    introduction=userinfo["role"]).first()
                if not userrole:
                    return {'code': 1, 'message': "无此用户角色，请填写正确内容！"}
                user.role = userrole
            if 'password' in userinfo and not userinfo['password']:
                user.password = userinfo['password']
            if userinfo['chinese_name']:
                user.chinese_name = userinfo['chinese_name']
            if userinfo['sbu']:
                sbu = Sbu.query.filter_by(name=userinfo['sbu']).first()
                if not sbu:
                    return {'code': 1, 'message': "无此事业部，请填写正确内容！"}
                user.sbu = sbu
            if userinfo['zhiwu']:
                user.zhiwu = userinfo['zhiwu']
            if userinfo['bumen']:
                user.bumen = userinfo['bumen']
            try:
                user.save()
            except Exception:
                return {'code': 1, 'message': "账户修改失败！"}
        return {'code': 20000, 'data': {'success': 1}}

class Accountlistargs(Resource):
    @auth.login_required
    @check_role('admin')
    def delete(self,username):            
        if not username:
            return {'code': 1, 'message': "账户删除失败！"}
        user = User.query.filter_by(username=username).first()
        if not user:
            return {'code': 1, 'message': "账户删除失败！"}
        try:
            user.delete()
        except Exception:
            return {'code': 1, 'message': "账户删除失败！"}
        return {'code': 20000, 'data': {'success': 1}}

api.add_resource(Test, '/test', endpoint='testapi')
api.add_resource(Login, '/login', endpoint='loginapi')
api.add_resource(Logout, '/prod-api/user/logout', endpoint='logoutapi')
api.add_resource(Token, '/prod-api/user/get_token', endpoint='tokenapi')
api.add_resource(Roleget, '/prod-api/user/info', endpoint='rolegetapi')
api.add_resource(Accountlist, '/prod-api/table/adminlist',
                 endpoint='accountlistapi')
api.add_resource(Accountlistargs, '/prod-api/table/adminlist/<username>',
                 endpoint='accountlistargsapi')
